package com.longe.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisUtil {

    private static RedisClient client = new RedisClient();

   /* public static void put(final String key, final Object value, final Integer seconds) {

        client.callRedis(new RedisHandler<Object>() {
            @Override
            public Object execute(Jedis jedis) {
                String json = JSON.toJSONString(value);
                jedis.set(key, json);
                jedis.expire(key, seconds);
                return null;
            }
        });

    }

    public static <T> T get(final String key, final Class<T> clazz) {
        return client.callRedis(new RedisHandler<T>() {
            @Override
            public T execute(Jedis jedis) {
                String value = jedis.get(key);
                return StringUtils.isBlank(value) ? null : JSONObject.parseObject(value, clazz);
            }
        });
    }

    public static Long del(final String key) {
        return client.callRedis(new RedisHandler<Long>() {
            @Override
            public Long execute(Jedis jedis) {
                return jedis.del(key);
            }
        });
    }*/

   public static void put(final byte[] key, final byte[] value, final Integer seconds) {

        client.callRedis(new RedisHandler<Object>() {
            @Override
            public Object execute(Jedis jedis) {
                jedis.set(key, value);
                jedis.expire(key, seconds);
                return null;
            }
        });

    }

    public static byte[] get(final byte[] key) {
        return client.callRedis(new RedisHandler<byte[]>() {
            @Override
            public byte[] execute(Jedis jedis) {
                byte[] value = jedis.get(key);
                return value;
            }
        });
    }

    public static Long del(final byte[] key) {
        return client.callRedis(new RedisHandler<Long>() {
            @Override
            public Long execute(Jedis jedis) {
                return jedis.del(key);
            }
        });
    }

    static class RedisClient {

        private static JedisPool jedisPool = SpringContextUtil.getContext().getBean(JedisPool.class);

        public <T> T callRedis(RedisHandler<T> handler) {
            Jedis jedis = jedisPool.getResource();
            try {
                return (T) handler.execute(jedis);
            } finally {
                jedis.close();
            }
        }

    }

    interface RedisHandler<T> {

        /**
         * Redis执行方法
         * @param jedis
         * @return
         */
        T execute(Jedis jedis);

    }

}